package com.example.myapplication;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.data.StatisticDefinition;
import com.esri.arcgisruntime.data.StatisticRecord;
import com.esri.arcgisruntime.data.StatisticType;
import com.esri.arcgisruntime.data.StatisticsQueryParameters;
import com.esri.arcgisruntime.data.StatisticsQueryResult;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.layers.ArcGISMapImageLayer;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.LayerList;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.ClassBreaksRenderer;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;


public class MainActivity extends AppCompatActivity {
    private static String TAG = "测试";
    private MapView mMapView;
    private String ip = "";
    private ServiceFeatureTable serviceFeatureTable;
    private ArcGISMapImageLayer mapImageLayer;

    private Callout mCallout;
    private int counter = 0;
    private double[] result = new double[5];
    private FeatureLayer featureLayer;
    private String sql_all = "0";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        mMapView = findViewById(R.id.mapView);
        ArcGISMap map = new ArcGISMap();
        ip = getIntent().getStringExtra("ip");
        String name = getIntent().getStringExtra("name");
        setTitle(name);
        mMapView.setMap(map);
        mCallout = mMapView.getCallout();
        Viewpoint viewpoint;
        if ("昌吉市".equals(name)) {
            viewpoint = new Viewpoint(new Envelope(86.93486287100006, 43.55018512700008, 87.52057841100003, 44.72838423600007, SpatialReference.create(4326)));
            mapImageLayer = new ArcGISMapImageLayer(ip + getResources().getString(R.string.changji_map));
            serviceFeatureTable = new ServiceFeatureTable(ip +
                    getResources().getString(R.string.changji_feature));
        } else {
            viewpoint = new Viewpoint(new Envelope(85.75347957500009, 43.845286470000076, 86.55444473900008, 45.25096347300007, SpatialReference.create(4326)));
            mapImageLayer = new ArcGISMapImageLayer(ip + getResources().getString(R.string.mage_map));
            serviceFeatureTable = new ServiceFeatureTable(ip +
                    getResources().getString(R.string.mage_feature));
        }
        map.setInitialViewpoint(viewpoint);
        mMapView.getMap().getOperationalLayers().add(mapImageLayer);
        featureLayer = new FeatureLayer(serviceFeatureTable);
        featureLayer.setRenderer(getRender());
        featureLayer.setVisible(false);

        mMapView.getMap().getOperationalLayers().add(featureLayer);

        listener();

    }

    public void search(View view) {

        //关闭弹出框
        if (mCallout.isShowing()) {
            mCallout.dismiss();
        }

        mMapView.getGraphicsOverlays().clear();

        mapImageLayer.setVisible(false);
        EditText editText = findViewById(R.id.editText);
        String govName = String.valueOf(editText.getText());
        String sql;
        if ("昌吉市".contentEquals(getTitle())) {
            sql = "村名称 = '" + govName + "'";
        } else {
            sql = "ZLDWMC = '" + govName + "'";
        }
        Log.e(TAG, sql);

        if (!"全部".equals(govName)) {
            featureLayer.setDefinitionExpression(sql);
            sql_all = sql;
        } else {
            featureLayer.setDefinitionExpression("1 = 1");
            sql_all = "1 = 1";
        }
        featureLayer.setVisible(true);
    }

    /**
     * 获取分类样式
     *
     * @return
     */
    private ClassBreaksRenderer getRender() {
        List<ClassBreaksRenderer.ClassBreak> breaks = new ArrayList<>();

        breaks.add(
                new ClassBreaksRenderer.ClassBreak
                        ("五级地", "五级地", 11, 13,
                                new SimpleFillSymbol
                                        (SimpleFillSymbol.Style.SOLID, getResources().getColor(R.color.level5),
                                                new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLACK, 1))));
        breaks.add(
                new ClassBreaksRenderer.ClassBreak
                        ("四级地", "四级地", 13, 15,
                                new SimpleFillSymbol
                                        (SimpleFillSymbol.Style.SOLID, getResources().getColor(R.color.level4),
                                                new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLACK, 1))));
        breaks.add(
                new ClassBreaksRenderer.ClassBreak
                        ("三级地", "三级地", 15, 17,
                                new SimpleFillSymbol
                                        (SimpleFillSymbol.Style.SOLID, getResources().getColor(R.color.level3),
                                                new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLACK, 1))));
        breaks.add(
                new ClassBreaksRenderer.ClassBreak
                        ("二级地", "二级地", 17, 19,
                                new SimpleFillSymbol
                                        (SimpleFillSymbol.Style.SOLID, getResources().getColor(R.color.level2),
                                                new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLACK, 1))));
        breaks.add(
                new ClassBreaksRenderer.ClassBreak
                        ("一级地", "一级地", 19, 23,
                                new SimpleFillSymbol
                                        (SimpleFillSymbol.Style.SOLID, getResources().getColor(R.color.level1),
                                                new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLACK, 1))));
        return new ClassBreaksRenderer("xx", breaks);
    }

    public void statistic(View view) {

        counter = 0;
        if (!"0".equals(sql_all)) {
            statistic(0, sql_all + "and xx >=19");
            statistic(1, sql_all + "and xx between 17 and 19");
            statistic(2, sql_all + "and xx between 15 and 17");
            statistic(3, sql_all + "and xx between 13 and 15");
            statistic(4, sql_all + "and xx < 13");
        }
    }

    private void statistic(Integer index, String sql) {
        StatisticDefinition statisticDefinition1 = new StatisticDefinition("mj", StatisticType.SUM);

        List<StatisticDefinition> definitions = new ArrayList<>();
        definitions.add(statisticDefinition1);
        StatisticsQueryParameters queryParameters = new StatisticsQueryParameters(definitions);
        queryParameters.setWhereClause(sql);

        ListenableFuture<StatisticsQueryResult> statQueryResultFuture = serviceFeatureTable.queryStatisticsAsync(queryParameters);
        statQueryResultFuture.addDoneListener(() -> {
            try {
                StatisticsQueryResult statQueryResult = statQueryResultFuture.get();
                // get iterator from the result
                Iterator<StatisticRecord> statisticRecordIterator = statQueryResult.iterator();

                // build a result string for display
                while (statisticRecordIterator.hasNext()) {
                    Map<String, Object> statisticsMap = statisticRecordIterator.next().getStatistics();
                    for (Map.Entry<String, Object> stat : statisticsMap.entrySet()) {
                        counter++;
                        if (stat.getValue() == null) {
                            this.result[index] = 0;
                        } else {
                            this.result[index] = (Double) stat.getValue();
                        }
                        Log.e(TAG, index + ":" + this.result[index]);
                        if (counter == 5) {
                            new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("统计结果(平方米)")
                                    .setMessage("一级" + this.result[0] + "\n"
                                            + "二级" + this.result[1] + "\n"
                                            + "三级" + this.result[2] + "\n"
                                            + "四级" + this.result[3] + "\n"
                                            + "五级" + this.result[4] + "\n")
                                    .setPositiveButton("确定", null)
                                    .show();
                        }

                    }
                }
            } catch (InterruptedException | ExecutionException e) {
                Toast.makeText(getApplicationContext(), "查询失败", Toast.LENGTH_LONG).show();
                Log.e(TAG, e.getMessage());
                e.printStackTrace();
            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    private void listener() {
        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {

                //关闭弹出框
                if (mCallout.isShowing()) {
                    mCallout.dismiss();
                }

                mMapView.getGraphicsOverlays().clear();

                final Point clickPoint = mMapView
                        .screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));

//                int tolerance = 10;
//                double mapTolerance = tolerance * mMapView.getUnitsPerDensityIndependentPixel();
//                Envelope envelope = new Envelope(clickPoint.getX() - mapTolerance, clickPoint.getY() - mapTolerance,
//                        clickPoint.getX() + mapTolerance, clickPoint.getY() + mapTolerance, mMapView.getSpatialReference());
                //查询参数设置
                QueryParameters query = new QueryParameters();
                query.setGeometry(clickPoint);
                query.setSpatialRelationship(QueryParameters.SpatialRelationship.WITHIN);
                final ListenableFuture<FeatureQueryResult> future;

                future = serviceFeatureTable
                        .queryFeaturesAsync(query, ServiceFeatureTable.QueryFeatureFields.LOAD_ALL);


                future.addDoneListener(() -> {
                    try {
                        FeatureQueryResult result = future.get();
                        Iterator<Feature> iterator = result.iterator();
                        TextView calloutContent = new TextView(getApplicationContext());

                        calloutContent.setTextColor(Color.BLACK);
                        calloutContent.setSingleLine(false);
                        calloutContent.setVerticalScrollBarEnabled(true);
                        calloutContent.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
                        calloutContent.setMovementMethod(new ScrollingMovementMethod());
                        calloutContent.setLines(5);
                        Feature feature;

                        while (iterator.hasNext()) {
                            feature = iterator.next();
                            GraphicsOverlay graphicsOverlay = new GraphicsOverlay();
                            SimpleFillSymbol simpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.NULL, Color.RED, new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.RED, 3));
                            graphicsOverlay.getGraphics().add(new Graphic(feature.getGeometry(), simpleFillSymbol));
                            mMapView.getGraphicsOverlays().add(graphicsOverlay);
                            // create a Map of all available attributes as name value pairs
                            Map<String, Object> attr = feature.getAttributes();
                            Set<String> keys = attr.keySet();
                            for (String key : keys) {
                                Object value = attr.get(key);
                                if (value instanceof GregorianCalendar) {
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.CHINA);
                                    value = simpleDateFormat.format(((GregorianCalendar) value).getTime());
                                }
                                if ("xx".equals(key)) {
                                    calloutContent.append("土地等级 | " + GetLevel(Double.parseDouble(attr.get(key).toString())) + "\n");
                                } else {
                                    calloutContent.append(key + " | " + value + "\n");
                                }
                            }
                            Envelope envelope1 = feature.getGeometry().getExtent();
                            mMapView.setViewpointGeometryAsync(envelope1);
                            mCallout.setLocation(clickPoint);
                            mCallout.setContent(calloutContent);
                            mCallout.show();
                        }
                    } catch (Exception e1) {
                        Log.e(getResources().getString(R.string.app_name), "Select feature failed: " + e1.getMessage());
                    }
                });

                return super.onSingleTapConfirmed(e);
            }
        });
    }

    private static Integer GetLevel(double val) {
        if (val < 13) {
            return 5;
        } else if (val < 15) {
            return 4;
        } else if (val < 17) {
            return 3;
        } else if (val < 19) {
            return 2;
        } else {
            return 1;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.dispose();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.pause();
    }

    public void changeLevel(View view) {
        switch (view.getId()) {
            case R.id.level1:
                break;
            case R.id.level2:
                break;
            case R.id.level3:
                break;
            case R.id.level4:
                break;
            case R.id.level5:
                break;
            default:
                break;
        }
    }
}
